package view.swing.tiles;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.InputEvent;

import javax.swing.JComponent;
import javax.swing.TransferHandler;

import view.swing.tiles.TileDragDroppable.AllowedState;

public class TileDragHandler extends TransferHandler {

    /**
     * 
     */
    private static final long serialVersionUID = 3673541460913052369L;

    @Override
    public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
        if (comp instanceof TileDragDroppable) {
            for (DataFlavor df : transferFlavors) {
                if (df.equals(TileTransferable.DATA_FLAVOR))
                    return true;
            }
        }
        return false;
    }

    @Override
    protected Transferable createTransferable(JComponent c) {
        if (c instanceof TileDragDroppable) {
            return new TileTransferable(((TileDragDroppable) c));
        }
        return null;
    }

    @Override
    public int getSourceActions(JComponent c) {
        return MOVE;
    }

    @Override
    public void exportAsDrag(JComponent comp, InputEvent e, int action) {
        if (comp instanceof TileDragDroppable
                && ((TileDragDroppable) comp).hasTileHere()
                && ((TileDragDroppable) comp).getAllowedState() == AllowedState.BOTH) {
            super.exportAsDrag(comp, e, action);
        } else {
            e.consume();
        }
    }

    @Override
    public boolean importData(JComponent comp, Transferable t) {
        if (comp instanceof TileDragDroppable
                && t.isDataFlavorSupported(TileTransferable.DATA_FLAVOR)
                && (((TileDragDroppable) comp).getAllowedState() == AllowedState.DROP || ((TileDragDroppable) comp)
                        .getAllowedState() == AllowedState.BOTH)) {
            try {
                Placeur.drop((TileDragDroppable) t
                        .getTransferData(TileTransferable.DATA_FLAVOR),
                        (TileDragDroppable) comp);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return false;
    }
}
